package com.sxpi.zixun.service.adminuser;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxpi.zixun.bo.AdminUserBo;
import com.sxpi.zixun.common.enums.AdminErrorResultEnum;
import com.sxpi.zixun.common.enums.AdminUserResultEnum;
import com.sxpi.zixun.common.enums.ResultStatusEnum;
import com.sxpi.zixun.common.ex.PugBusinessException;
import com.sxpi.zixun.common.ex.PugValidatorException;
import com.sxpi.zixun.common.utils.fn.asserts.Vsserts;
import com.sxpi.zixun.common.utils.pwd.MD5Util;
import com.sxpi.zixun.mapper.AdminUserMapper;
import com.sxpi.zixun.pojo.AdminRole;
import com.sxpi.zixun.pojo.AdminUser;
import com.sxpi.zixun.vo.AdminUserRegVo;
import com.sxpi.zixun.vo.AdminUserUpdateVo;
import com.sxpi.zixun.vo.AdminUserVo;
import com.sxpi.zixun.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 董伟豪
 * @Date: 2022/8/24 12:31
 */
@Service
@Slf4j
public class IAdminUserServiceImpl extends ServiceImpl<AdminUserMapper,AdminUser> implements IAdminUserService {

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @Override
    public AdminUser login(LoginVo loginVo) {
        LambdaQueryWrapper<AdminUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminUser::getAccount, loginVo.getUsername());
        AdminUser user = this.getOne(lambdaQueryWrapper);
        return user;
    }

    /**
     * 保存&修改后台用户管理
     * 数据库，操作的一定是实体类
     * @param adminUserRegVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminUserBo saveUpdateAdminUser(AdminUserRegVo adminUserRegVo) {
        AdminUser editUser = this.getById(adminUserRegVo.getId());
        if((adminUserRegVo != null && adminUserRegVo.getId() == null) || // 保存
                (editUser != null && !editUser.getAccount().equals(adminUserRegVo.getAccount()))){ // 修改
            // 查询账号是否已经存在
            LambdaQueryWrapper<AdminUser> adminUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            adminUserLambdaQueryWrapper.eq(AdminUser::getAccount,adminUserRegVo.getAccount());
            int count = this.count(adminUserLambdaQueryWrapper);
            // 根据账号查询用户是否已经注册，如果是注册的那么count一定是大于0的
            if(count > 0){
                throw new PugBusinessException(AdminUserResultEnum.ACCOUNT_REG_ERROR);
            }
        }
        // 保存数据转换成BO
        AdminUser adminUser = tranferBo(adminUserRegVo, AdminUser.class);
        if(Vsserts.isNotEmpty(adminUserRegVo.getPassword())){
            // 密码加密
            adminUser.setPassword(MD5Util.md5slat(adminUser.getPassword()));
        }else{
            // 把原始的密码放回去
            if(editUser != null && Vsserts.isNotEmpty(editUser.getPassword())){
                adminUser.setPassword(editUser.getPassword());
            }
        }
        // 入库 mybatis-plus在执行save/saveOrUpdate自动会返回保存数据以后id的值
        boolean flag = this.saveOrUpdate(adminUser);
        // 用户保存成功以后，在去绑定角色
        if(flag){
            // 绑定角色      查询用户是否已经绑定角色
            int count = this.baseMapper.countUserRole(adminUser.getId(),adminUserRegVo.getRoleId());
            if(count == 0){
                this.baseMapper.saveUserRole(adminUser.getId(),adminUserRegVo.getRoleId());
            }
        }
        // 返回
        return flag ? tranferBo(adminUser,AdminUserBo.class) : null;
    }

    /**
     * 这个代码是saveUpdateAdminUser之前的写法，单纯的添加！！！
     * gitee --- 管理员页面的删除
     * @param adminUserRegVo
     * @return
     */
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    public AdminUserBo saveUpdateAdminUserDeprecated(AdminUserRegVo adminUserRegVo) {
        // 查询账号是否已经存在
        LambdaQueryWrapper<AdminUser> adminUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminUserLambdaQueryWrapper.eq(AdminUser::getAccount,adminUserRegVo.getAccount());
        int count = this.count(adminUserLambdaQueryWrapper);
        // 根据账号查询用户是否已经注册，如果是注册的那么count一定是大于0的
        if(count > 0){
            throw new PugBusinessException(AdminUserResultEnum.ACCOUNT_REG_ERROR);
        }
        AdminUser adminUser = tranferBo(adminUserRegVo, AdminUser.class);
        // 密码加密
        adminUser.setPassword(MD5Util.md5slat(adminUser.getPassword()));
        // 入库 mybatis-plus在执行save/saveOrUpdate自动会返回保存数据以后id的值
        boolean flag = this.saveOrUpdate(adminUser);
        // 用户保存成功以后，在去绑定角色
        if(flag){
            // 绑定角色
            this.baseMapper.saveUserRole(adminUser.getId(),adminUserRegVo.getRoleId());
        }
        // 返回
        return flag ? tranferBo(adminUser,AdminUserBo.class) : null;
    }

    /**
     * 查询后台用户管理列表信息并分页
     * @param adminUserVo
     * @return
     */
    @Override
    public IPage<AdminUserBo> findAdminUserPage(AdminUserVo adminUserVo) {
        // 设置分页信息
        Page<AdminUser> adminUserPage = new Page<>(adminUserVo.getPageNo(),adminUserVo.getPageSize());
        // 设置查询条件
        LambdaQueryWrapper<AdminUser> adminUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询发布的 0 未发布  1 发布
        adminUserLambdaQueryWrapper.eq(adminUserVo.getStatus() != null,AdminUser::getStatus,adminUserVo.getStatus());
        // 多列搜索
/*  这种方式代码太冗余了
        adminUserLambdaQueryWrapper.like(Vsserts.isNotEmpty(adminUserVo.getKeyword()),AdminUser::getUsername,adminUserVo.getKeyword())
                .or().like(AdminUser::getAccount,adminUserVo.getKeyword());
*/
        adminUserLambdaQueryWrapper.and(Vsserts.isNotEmpty(adminUserVo.getKeyword()),wrapper ->{
            wrapper.like(AdminUser::getUsername,adminUserVo.getKeyword())
                    .or()
                    .like(AdminUser::getAccount,adminUserVo.getKeyword());
        });
        adminUserLambdaQueryWrapper.orderByDesc(AdminUser::getCreateTime);
        // 查询分页返回
        IPage<AdminUser> results = this.page(adminUserPage, adminUserLambdaQueryWrapper);
        return tranferPageBo(results, AdminUserBo.class);
    }

    /**
     * 查询用户对应的权限信息
     * @param userId
     * @return
     */
    @Override
    public List<String> findByUserPermission(Long userId) {
        return this.baseMapper.findByUserPermission(userId);
    }

    /**
     * 根据用户id查询角色Ids
     * @param userId
     * @return
     */
    @Override
    public List<Long> findByUserRikeIds(Long userId) {
        List<AdminRole> byUserRoles = this.baseMapper.findByUserRoles(userId);
        // 只返回Ids
        if(!CollectionUtils.isEmpty(byUserRoles)){
            return byUserRoles.stream().map(role->{
               return role.getId();
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 根据id删除后台用户管理 放入回收站
     * @param id
     * @return
     */
    @Override
    public int deleteAdminUserById(Long id) {
        // 只是判断给的id是否正确，能查出用户给的id肯定是规范的
        AdminUser user = this.getById(id);
        if(user != null) {
            AdminUser newUser = new AdminUser();
            newUser.setId(id);
            newUser.setIsdelete(1);
            this.updateById(newUser);
            return 1;
        }
        return 0;
    }

    /**
     * 物理删除暂时废弃
     * 根据id删除单条
     * @param id
     * @return
     */
    @Deprecated
    public int deleteAdminUserByIdDeprecated(Long id) {
        boolean b = this.removeById(id);
        return b ? 1 : 0;
    }

    /**
     * 更新状态
     * @param adminUserUpdateVo
     * @return
     */
    @Override
    public Boolean updateAdminUser(AdminUserUpdateVo adminUserUpdateVo) {
        AdminUser adminUser = tranferBo(adminUserUpdateVo, AdminUser.class);
        return updateById(adminUser);
    }

    /**
     * 根据后台用户管理ids批量删除后台用户管理
     * @param ids
     * @return
     */
    @Override
    public Boolean deleteBatchAdminUser(String ids) {
        try {
            // 1 : 把数据分割
            String[] strings = ids.split(",");
            // 2: 组装成一个List<AdminUser>
            List<AdminUser> adminUserList = Arrays.stream(strings).map(idStr -> {
                AdminUser adminuser = new AdminUser();
                // 逻辑删除
                adminuser.setIsdelete(1);
                adminuser.setId(new Long(idStr));
                return adminuser;
            }).collect(Collectors.toList());
            // 3: 批量删除
            return this.updateBatchById(adminUserList);
        } catch (Exception ex) {
            throw new PugValidatorException(ResultStatusEnum.SERVER_DB_ERROR);
        }
    }

    /**
     * 物理删除暂时废弃
     * 根据后台用户管理ids批量删除后台用户管理
     * @param ids
     * @return
     */
    @Deprecated
    public Boolean deleteBatchAdminUserDeprecated(String ids) {
        String[] strings = ids.split(",");
        List<String> stringIds = Arrays.asList(strings);
        this.removeByIds(stringIds);
        /*
        stringIds.stream().map(item->{
            return this.removeById(item);
        }).collect(Collectors.toList());
        */
        return true;
    }

    /**
     * 根据用户id获取角色
     * @param userId
     * @return
     */
    @Override
    public List<String> getRoleNames(Long userId) {
        List<AdminRole> byUserRoles = this.baseMapper.findByUserRoles(userId);
        if(!CollectionUtils.isEmpty(byUserRoles)){
            // return byUserRoles.stream().map(AdminRole::getRoleName).collect(Collectors.toList());
            return byUserRoles.stream().map(role -> {
                return role.getRoleName();
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 给用户绑定角色
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public int saveUserRole(Long userId, Long roleId) {
        // 查询用户是否已经绑定角色
        int count = this.baseMapper.countUserRole(userId,roleId);
        if(count == 0){
            return this.baseMapper.saveUserRole(userId,roleId);
        }
        return 0;
    }

    /**
     * 给用户解绑角色
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public int deleteUserRole(Long userId, Long roleId) {
        int count = this.baseMapper.countUserRole(userId,roleId);
        if(count > 0){
            return this.baseMapper.deleteUserRole(userId,roleId);
        }
        return 0;
    }


}
